<template>
    <div style=" position: relative;"> <el-card>
            <template #header>
                <!-- 搜索 -->
                <div>

                    <el-select style="width: 300px;" v-model="find_data.dataSetType" placeholder="请选择设置类型" clearable>
                        <el-option v-for="item in getDataSetType_list" :key="item.id" :label="item.text"
                            :value="item.id" />
                    </el-select>
                    <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                        icon="Search">搜索</el-button>
                </div>
                <!-- 功能按钮 -->
                <div style="margin-top:10px;">
                    <el-button @click="add_btn" type="primary" icon="SuccessFilled">添加</el-button>
                    <el-button @click="up_btn" type="warning" icon="WarnTriangleFilled">修改</el-button>
                    <el-button @click="del_btn" type="danger" icon="CircleCloseFilled">删除</el-button>
                </div>
            </template>
            <div>
                <el-table border @selection-change="selection_change_btn" height="67vh" ref="multipleTableRef"
                    :data="list_data" style="width: 100%">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />
                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">
                            <template v-if="item.field == 'dataSetType'" #="{ row, column, $index }">
                                <span>{{ dataSetType_api(row.dataSetType) }}</span>
                                <!-- row.dataSetType == 'INTEREAT_DEFAULT' ? '违约利息设置' : row.dataSetType ==
                                'RECOM_REWARD_POINT' ? '推荐巴士币奖' : row.dataSetType == 'SHARE_TITLE' ? '推荐人奖励设置' :
                                row.dataSetType == 'RECEIVE_AIRPORT_PERSON' ? '接机人设置' : row.dataSetType ==
                                    'CAR_DISPATCH_PERSON' ? '车辆调度' : row.dataSetType == 'BILL_DAY' ? '账单日' : row.dataSetType
                                        ==
                                        'REMIND_REPAYMENT_DAY' ? '还款提醒日' : row.dataSetType == 'LAST_REPAYMENT_DAY' ? '最后还款日'
                                        : row.dataSetType == 'HURRY_REPAYMENT_DAY' ? '催收日' : '暂无设置' -->
                            </template>

                            <template v-if="item.field == 'assist'" #="{ row, column, $index }">
                                <el-image style="width: 95px; height: 95px" :preview-teleported="true"
                                    :preview-src-list="[ImageUrl + row.assist]"
                                    :src="row.assist ? ImageUrl + row.assist : ''" fit="cover">
                                    <template #error>
                                        <div>
                                            <el-icon style="width: 95px; height: 95px">
                                                <Picture />
                                            </el-icon>
                                        </div>
                                    </template>
                                </el-image>

                            </template>

                            <template v-if="item.field == 'ocState'" #="{ row, column, $index }">
                                <span>{{ row.ocState == 'OPENED' ? '开启' : '关闭' }}</span>
                            </template>
                            <template v-if="item.field == 'val'" #="{ row, column, $index }">
                                <div v-if="row.dataSetType != 'GIVE_BSCOIN'">
                                    <span v-html="row.val"></span>
                                </div>
                                <div v-if="row.dataSetType == 'GIVE_BSCOIN'">
                                    <div>时间:{{ row.startTime + '-' + row.endTime }}</div>
                                    <div>推荐赠送:{{ row.val.split("-")[0] }}</div>
                                    <div>注册赠送:{{ row.val.split("-")[1] }}</div>
                                </div>
                            </template>

                        </el-table-column>
                    </template>
                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="find_data.page.pageNum" v-model:page-size="find_data.page.pageSize"
                    :page-sizes="[20, 50, 100, 200]" :background="true"
                    layout="prev, pager, next, jumper,->,sizes,total," :total="total" />
            </div>
        </el-card></div>
    <!-- 弹窗 -->
    <div>
        <!-- 表格筛选 -->
        <div style="position: absolute;top:75px;z-index: 2;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
            <el-icon @click="icon_btn" :size="20">
                <Setting />
            </el-icon>
            <div v-show="icon_off"
                style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                    <div>
                        <el-button-group style="display: flex; ">
                            <el-tooltip effect="dark" placement="bottom">
                                <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                            </el-tooltip>
                            <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                            <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                        </el-button-group>
                        <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                            <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                :key="item.field" v-model="item.off" :label="item.label" border>
                            </el-checkbox>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <!-- 添加修改 -->
        <el-dialog style="margin-top:5vh" v-model="add_off" :title="title" width="60%" :close-on-click-modal='false'>
            <el-form :model="add_data" label-width="130px" label-suffix="：">
                <el-form-item label="设置类型">
                    <el-select v-model="add_data.dataSetType" placeholder="设置类型" clearable>
                        <el-option v-for="item in getDataSetType_list" :key="item.id" :label="item.text"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="开关状态">
                    <el-switch v-model="add_data.ocState" />
                </el-form-item>
                <el-form-item label="设置值" v-if="add_data.dataSetType != 'GIVE_BSCOIN'">
                    <!-- <el-input autosize type="textarea" placeholder="请输入设置值" v-model="add_data.val" /> -->
                    <div style="border: 1px solid #ccc">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" />
                        <Editor style="height: 300px; overflow-y: hidden;" v-model="add_data.val"
                            @onCreated="handleCreated" />
                    </div>

                </el-form-item>
                <el-form-item label="开始时间" v-if="add_data.dataSetType == 'GIVE_BSCOIN'">
                    <el-date-picker format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                        :default-time="new Date(2000, 1, 1, 0, 0, 0)" v-model="add_data.startTime" type="datetime"
                        placeholder="开始时间" />

                </el-form-item>
                <el-form-item label="结束时间" v-if="add_data.dataSetType == 'GIVE_BSCOIN'">
                    <el-date-picker format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                        :default-time="new Date(2000, 1, 1, 23, 59, 59)" v-model="add_data.endTime" type="datetime"
                        placeholder="结束时间" />

                </el-form-item>
                <el-form-item label="推荐赠送" v-if="add_data.dataSetType == 'GIVE_BSCOIN'">
                    <!-- <el-input type="number" clearable v-model="val1" style="width: 240px" placeholder="巴士币推荐赠送" /> -->
                    <el-input-number v-model="val1" :precision="0" :step="1" />
                </el-form-item>
                <el-form-item label="注册赠送" v-if="add_data.dataSetType == 'GIVE_BSCOIN'">

                    <el-input-number v-model="val2" :precision="0" :step="1" />
                </el-form-item>
                <el-form-item label="图片" :required="false">
                    <el-upload class="avatar-uploader" :action="ImageUrl_upload" :headers="{ token: GET_TOKEN() }"
                        :data="{ ftype: 'BACK_SET_DATA_IMG', files: rawFile_list }" :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload" :show-file-list="false">
                        <img v-if="add_data.headBannerImgUrl" :src="ImageUrl + add_data.headBannerImgUrl"
                            class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <!-- <el-upload v-model:file-list="add_data.headBannerImgUrl" :action="ImageUrl_upload"
                        :headers="{ token: GET_TOKEN() }" :data="{ ftype: 'BACK_SET_DATA_IMG', files: rawFile_list }"
                        list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
                        :before-upload="beforeAvatarUpload">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <el-dialog v-model="dialogVisible">
                        <img w-full :src="dialogImageUrl" alt="Preview Image" />
                    </el-dialog> -->
                </el-form-item>

                <el-form-item label="备注" :required="false">
                    <el-input show-word-limit maxlength="30" type="textarea" v-model="add_data.note" />
                </el-form-item>

            </el-form>
            <el-button @click="ok_btn" style="margin-left:50vw" type="primary">确认提交</el-button>
        </el-dialog>
    </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入富文本编辑器的 CSS 文件
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import CircularJSON from 'circular-json'
import Sortable from 'sortablejs';
import { ref, reactive, onMounted, computed, shallowRef } from 'vue'
import { getDataSetList, getDataSetType, adupDataSet, delDataSet, adupPrivateSet, getPrivateSetList } from '@/api/customer_list.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { companyRole_data, ImageUrl, FileType, ImageUrl_upload } from '@/utils/common.js'
import { GET_TOKEN } from '@/utils/token.js'
onMounted(async () => {
    let constdata = JSON.parse(localStorage.getItem('constdata'))
    if (constdata) {
        find_data.dataSetType = constdata.dataSetType

    }
    getDataSetType({}).then(res => {
        getDataSetType_list.value = res.data
    })

    getPrivateSetList({
        find: '常量数据设置',
        page: {
            pageNum: 1,
            pageSize: 999,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            table_data_list_new.value = table_data_list
        }
    })


    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);

            // 重新赋值给列数组
            // let cols = that.U.scopy(that.fields);
            // let list = cols.filter(it => { return it.show; });
            // that.$emit('saveSet', {dgName: that.dgName, cols: list});
        }
    })

    await list_api()
})
const dataSetType_api = (e) => {
    let data = ''
    for (let i = 0; i < getDataSetType_list.value.length; i++) {
        if (e == getDataSetType_list.value[i].id) {
            data = getDataSetType_list.value[i].text
        }
    }
    return data
}
// 富文本
const editorRef = shallowRef()
const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

//#endregion
//#region 表格数据处理
const table_data_list = reactive([
    { label: '设置类型', field: 'dataSetType', width: 130, off: true },
    { label: '设置值', field: 'val', width: '', off: true },
    { label: '图片', field: 'assist', width: 165, off: true },
    { label: '状态', field: 'ocState', width: 85, off: true },
    { label: '备注', field: 'note', width: 200, off: true },
    { label: '添加时间', field: 'addTime', width: 165, off: true },
])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {
    console.log(table_data_list)
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))
    console.log(table_data_list)
    console.log(table_data_list_new.value)
}
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '常量数据设置',
        tbNum: "constdata",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion


//#region 分页列表
const list_data = ref([])
const find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 20,
    },
    dataSetType: ''
})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.page.pageNum = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}

const list_api = () => {

    getDataSetList(find_data).then(res => {
        list_data.value = res.data.list
        total.value = res.data.total
    })
}
//#endregion

//#region 添加
const add_off = ref(false)
const title = ref('添加常量数据设置')
const getDataSetType_list = ref([])
const add_data = reactive({
    dataSetType: '',
    headBannerImgUrl: '',
    id: "",
    note: "",
    ocState: "",
    val: "",
    endTime: "",
    startTime: "",
})
const val1 = ref(0)
const val2 = ref(0)
const add_btn = () => {
    title.value = '添加常量数据设置'
    add_data.dataSetType = ''
    add_data.headBannerImgUrl = ''
    add_data.id = ''
    add_data.note = ''
    add_data.ocState = true
    add_data.val = ''
    add_data.endTime = ''
    add_data.startTime = ''
    val1.value = 0
    val2.value = 0
    rawFile_list.value = []


    add_off.value = true

}

const rawFile_list = ref([])
// const dialogImageUrl = ref('')
// const dialogVisible = ref(false)
// const handleRemove = (uploadFile, uploadFiles) => {
//     console.log(uploadFile, uploadFiles)
//     console.log(add_data.headBannerImgUrl)
// }

// const handlePictureCardPreview = (uploadFile) => {
//     dialogImageUrl.value = uploadFile.url
//     dialogVisible.value = true
// }


const handleAvatarSuccess = (response, uploadFile) => {
    add_data.headBannerImgUrl = response.data.file.url
}

const beforeAvatarUpload = (rawFile) => {
    rawFile_list.value = []
    if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/gif') {
        if (rawFile.size / 1024 / 1024 > 5) {
            ElMessage.error('图片大小不能大于5M!')
            return false
        }
    } else {
        ElMessage.error('请上传图片!')
        return false
    }

    rawFile_list.value.push(rawFile)
    return true

}


//#endregion

//#region 表格选择
const table_list = ref([])
const selection_change_btn = (e) => {
    table_list.value = e
    console.log(e)
}
//#endregion
//#region 修改
const up_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }

    title.value = '修改常量数据设置'
    add_data.dataSetType = table_list.value[0].dataSetType
    add_data.headBannerImgUrl = table_list.value[0].assist
    add_data.id = table_list.value[0].id
    add_data.note = table_list.value[0].note
    add_data.ocState = table_list.value[0].ocState == "OPENED" ? true : false
    add_data.val = table_list.value[0].val

    add_data.endTime = table_list.value[0].endTime
    add_data.startTime = table_list.value[0].startTime
    if (table_list.value[0].val) {
        if (table_list.value[0].dataSetType == 'GIVE_BSCOIN') {
            val1.value = Number(table_list.value[0].val.split("-")[0])
            val2.value = Number(table_list.value[0].val.split("-")[1])
        }

    }

    rawFile_list.value = []


    add_off.value = true
}
//#endregion

// 提交
const ok_btn = () => {
    if (!add_data.dataSetType) {
        return ElMessage({
            message: '请选择设置类型',
            type: 'warning',
        })
    } else if (add_data.dataSetType != 'GIVE_BSCOIN') {
        if (!add_data.val) {
            return ElMessage({
                message: '请输入设置值',
                type: 'warning',
            })
        }

    }


    if (title.value == '添加常量数据设置') {
        let ps = {
            dataSetType: add_data.dataSetType,
            headBannerImgUrl: add_data.headBannerImgUrl,
            note: add_data.note,
            ocState: "",
            val: add_data.val,
            startTime: add_data.startTime,
            endTime: add_data.endTime,
        }
        if (add_data.ocState) {
            ps.ocState = 'OPENED'
        } else {
            ps.ocState = 'CLOSED'
        }
        if (ps.dataSetType == 'GIVE_BSCOIN') {
            ps.val = val1.value + '-' + val2.value
        } else {
            ps.val = add_data.val
        }
        // let arr = []
        // for (let i = 0; i < add_data.headBannerImgUrl.length; i++) {
        //     if (add_data.headBannerImgUrl[i].response.code == 1) {
        //         arr.push(add_data.headBannerImgUrl[i].response.data.file.url)
        //     }

        // }
        // ps.headBannerImgUrl = arr.join(',')

        adupDataSet(ps).then(res => {
            if (res.code == 1) {
                list_api()
                add_off.value = false
                return ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            } else {
                return ElMessage({
                    message: res.msg,
                    type: 'warning',
                })
            }
        })
    } else {
        let ps = {
            dataSetType: add_data.dataSetType,
            headBannerImgUrl: add_data.headBannerImgUrl,
            note: add_data.note,
            ocState: "",
            val: add_data.val,
            startTime: add_data.startTime,
            endTime: add_data.endTime,
            id: add_data.id,
        }
        if (add_data.ocState) {
            ps.ocState = 'OPENED'
        } else {
            ps.ocState = 'CLOSED'
        }
        if (ps.dataSetType == 'GIVE_BSCOIN') {


            ps.val = val1.value + '-' + val2.value
        } else {
            ps.val = add_data.val


        }

        adupDataSet(ps).then(res => {
            if (res.code == 1) {
                list_api()
                add_off.value = false
                return ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            } else {
                return ElMessage({
                    message: res.msg,
                    type: 'warning',
                })
            }
        })
    }
}
//#region 搜索
const search_btn = () => {

    localStorage.setItem('constdata', CircularJSON.stringify(find_data))
    list_api()
}
//#endregion

//#region 删除
const del_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }

    ElMessageBox.confirm(
        '是否确认删除客户?',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            delDataSet({
                ids: [table_list.value[0].id]
            }).then(res => {
                if (res.code == 1) {
                    list_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {
            if (e == 'cancel') {
                ElMessage({
                    type: 'warning',
                    message: '取消删除成功',
                })
            }

        })

}
//#endregion
</script>

<style scoped lang='scss'></style>
<style>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}


.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
}
</style>
<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}

.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
